package com.cslc.wechat.common.action;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.cslc.wechat.bind.action.BindAction;
import com.cslc.wechat.common.dto.message.RespTextMessage;
import com.cslc.wechat.common.mp.MpInfo;
import com.cslc.wechat.util.MessageUtil;
import com.cslc.wechat.util.SignUtil;

/**
 * 请求与相应消息的服务类
 * @author keliangliang
 *
 */
public class RouteAction {
	
	private static Logger logger = Logger.getLogger(RouteAction.class.getName());
	static final String SUBSCRIBE_MSG_HEADER = "您好！欢迎关注中国体育彩票官方微信故障申告微信账号：\n";
	
	static final String SUBSCRIBE_MSG_BODY = "绑定账号后，您将会：" + "\n" + 
			"1.实时上传您当前遇到的故障" + "\n" +
			"2.第一时间回馈并解决您的问题" + "\n";
	static final String BIND_TIPS = "绑定小贴士：\n" +
			"1.在您的销售终端点击生成二维码\n" +
			"2.返回微信主页面\n" + 
			"3.点击右上角+扫一扫";
	static final String NEWLINE = "\r\n";
	private BindAction bindAction;
	public BindAction getBindAction() {
		return bindAction;
	}

	public void setBindAction(BindAction bindAction) {
		this.bindAction = bindAction;
	}

	/**
	 * 处理微信发来的请求
	 * @param request
	 * @return
	 */
	public  String processRequest(HttpServletRequest request) {
		 String respMessage = null; 
		  //回复文本消息  
         RespTextMessage textMessage = new RespTextMessage();
	        try { 
	            // 默认返回的文本消息内容  
	           //String respContent = "请求处理异常，请稍候尝试！"; 
	        	String respContent = "";
	  
	            // xml请求解析  
	            Map<String, String> requestMap = MessageUtil.parseXml(request);  
	            
	            // 发送方帐号（open_id）  
	            String fromUserName = requestMap.get("FromUserName");  
	            logger.info("FromUserName:"+fromUserName);
	            // 公众帐号  
	            String toUserName = requestMap.get("ToUserName"); 
	            logger.info("ToUserName:"+toUserName);
	            // 消息类型  
	            String msgType = requestMap.get("MsgType");
	            logger.info("MsgType:"+msgType);
	            //事件类型
	            String event = requestMap.get("Event");
	            logger.info("Event:"+event);
	              
	            textMessage.setToUserName(fromUserName);  
	            textMessage.setFromUserName(toUserName);  
	            textMessage.setCreateTime(new Date().getTime());  
	            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
	            textMessage.setFuncFlag(0);  	            
	   
	            // 事件推送  
	            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
	                // 事件类型  
	                String eventType = requestMap.get("Event");  
	                logger.info("eventType："+eventType);
	               
	                //点击关注，分为不带参数二维码关注和带参数二维码关注
	                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { 
	                	//事件key值
	                	String eventKey = requestMap.get("EventKey");
	                	//将用户信息更新至数据库
	                	bindAction.subscribe(fromUserName);
	                	//当通过扫一扫不带参数二维码点击关注时，事件key值为空
	                	if(eventKey.equals("")) {
	                		respContent = "欢迎关注体彩报障系统(通过扫公众号名片关注，即不带任何参数)";
	                	}
	                	//当通过扫一扫带参数的二维码点击关注时，事件key值是qrscene_为前缀，后面为二维码的参数值
	                	else {
	                		//终端编码
	                		String terminalNo = eventKey.replaceAll("\\D", "");
	                		respContent = createBindLink(fromUserName,terminalNo);
	                	}
	                	
	                	//respContent=SUBSCRIBE_MSG_HEADER + NEWLINE +SUBSCRIBE_MSG_BODY + NEWLINE + BIND_TIPS;
	                	textMessage.setContent(respContent);
	                	respMessage = MessageUtil.textMessageToXml(textMessage);
	                }
	                  //扫一扫绑定终端，如果用户已经关注公众号，则微信会将带场景值扫描事件推送给开发者。 
	                 if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
	                	//事件key值
	                	String eventKey = requestMap.get("EventKey");
	                	logger.info("eventKey:"+eventKey);
	                	String terminalNo = eventKey;
	                	logger.info("terminalNo:"+terminalNo);

	                	respContent = createBindLink(fromUserName,terminalNo);

	                	textMessage.setContent(respContent);
	                	respMessage = MessageUtil.textMessageToXml(textMessage);
	                	
	                 }
	                 //扫码绑定终端
	                 /*else if (eventType.equals(MessageUtil.EVENT_TYPE_SCANCODE_PUSH)) {
		            }*/
	                // 取消关注  
	                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
	                    //解除绑定
	                	bindAction.unsubscribe(fromUserName);
	                	logger.info(fromUserName + "用户取消关注，解除绑定成功！");
	                	return null;
	                }
	                // 自定义菜单点击事件,注意,获取点击事件的key时有延迟,取消关注后再次关注可及时更新  
	                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
	                    String key = requestMap.get("EventKey");
	                    logger.info("key : " + key);
	                   
	                    //事件/故障上报
	                   if(key.equals("1_1_event_report")) {
	                	   logger.info("故障上报");
	                	   //respContent = eventReport(fromUserName);
	                   }
	                   if(key.equals("2_1_my_report")) {
	                    	respContent = "请<a href=\"" + MpInfo.HOST + "/my_report.jsp?OpenId==" + fromUserName + "\">点击这里</a>查看故障上报历史信息！";
	                    }
	                    else if(key.equals("3_2_unbind")) {
                  	        respContent = unbindTerminal(fromUserName);
                        }
	                    else if(key.equals("3_1_check")) {
	                    	respContent = showTerminalInfo(fromUserName);
	                    }
	                    textMessage.setContent(respContent);
	                    respMessage = MessageUtil.textMessageToXml(textMessage);
	                }
	                 
	                   
	            }  else{ //当用户发任意消息时
	            	String Content = requestMap.get("Content");
	            	logger.info("Content : " + Content);
	            	
	            	textMessage.setContent("请通过菜单使用本服务！");
	            	respMessage = MessageUtil.textMessageToXml(textMessage);
	            }
	              
	        } catch (Exception e) {  
	            logger.error(e.getMessage());
	            textMessage.setContent("请求处理异常，请稍候尝试！");
            	respMessage = MessageUtil.textMessageToXml(textMessage);
	        }  
	        return respMessage; 
	}

	private String createBindLink(String openid, String terminalNo) {
		logger.debug("该微信号未绑定");
		String timestamp = String.valueOf(System.currentTimeMillis());
		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
		String bindLink = "<a href=\"" + MpInfo.HOST + "/validate?terminalNo=%s&openid=%s&signature=%s&timestamp=%s\">点击这里，立即绑定您的终端</a>\n";
		bindLink = String.format(bindLink, terminalNo, openid, signature, timestamp);
		return bindLink;
	}

	@SuppressWarnings("unused")
	private static String createRespMsg(String bindLink) {
		StringBuilder builder = new StringBuilder();
		builder.append(SUBSCRIBE_MSG_HEADER);
		builder.append(NEWLINE);
		
		builder.append(NEWLINE);
		builder.append(SUBSCRIBE_MSG_BODY);
		builder.append(bindLink);
		builder.append(NEWLINE);
		
		builder.append(BIND_TIPS);
		return builder.toString();
	}
	
	/**
	 * 解除绑定
	 * @param openid
	 * @return
	 */
	private String unbindTerminal(String openid) {
		return "";    		
		//return terminalAction.unbindTerminal(openid);
	}
	
	/**
	 * 查看终端信息
	 * @param openid
	 * @return
	 */
	private String showTerminalInfo(String openid) {    		
		//return terminalAction.showTerminalInfo(openid);
		return "";
	}
	
//	/**
//	 * 终端绑定
//	 * @param openid
//	 * @param terminalNo 
//	 * @return
//	 */
//	private static String terminalBind(String openid, String terminalNo) {
//		String respContent = null;
//		User user = userDAO.findById(openid);
//		
//		//该微信号未绑定过
//		if(user == null) {
//    		logger.info("该微信号未绑定");
//    		String timestamp = String.valueOf(System.currentTimeMillis());
//    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
//    		String bindLink = "<a href=\"" + MpInfo.HOST + "/servlet/BindServlet?terminalNo=%s&OpenId=%s&signature=%s&timestamp=%s\">点击这里，立即绑定您的终端</a>\n";
//    		bindLink = String.format(bindLink, terminalNo, openid, signature, timestamp);
//    		respContent = createRespMsg(bindLink);
//    		logger.info("绑定确认url: " + respContent);
//    	}
//		//已绑定
//    	else {
//    		logger.info("该微信号已绑定过");
//    		respContent = "请勿重复绑定";
//    	}
//    		
//		return respContent;
//	}
//	/**
//	 * 故障上报历史信息查看
//	 * @param fromUserName
//	 * @return
//	 */
//	private static String reportCheck(String openid) {
//		String respContent = null;
//		User user = userDAO.findById(openid);
//		
//		//该微信号未绑定过
//		if(user == null) {
//    		logger.info("该微信号未绑定");
//    		respContent = createRespMsg(NEWLINE);
//    		logger.info("绑定确认url: " + respContent);
//    	}
//		//已绑定
//    	else {
//    		logger.info("该微信号已绑定过");
//    		String timestamp = String.valueOf(System.currentTimeMillis());
//    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
//    		respContent = "<a href=\"" + MpInfo.HOST + "/my_report.jsp\">请戳这里</a>查看故障上报历史信息！";
//    		respContent = String.format(respContent, openid, timestamp, signature);
//    	}
//    		
//		return respContent;
//	}
	/**
	 * 解除绑定
	 * @param openid
	 * @return
	 *//*
	private static String unbend(String openid) {
		String respContent = null;
		User user = userDAO.findById(openid);
		//该微信号未绑定过
		if(user == null) {
    		logger.info("该微信号未绑定");
    		respContent = createRespMsg(NEWLINE);
    	}
		//已绑定
    	else {
    		logger.info("该微信号已绑定过");
    		//解除绑定成功
    		if(userDAO.unbendUser(openid)) {
    			logger.info(openid + " 解除绑定成功");
    			respContent = "成功解除绑定！";
    		}
    		else {
    			logger.info(openid + " 解除绑定失败");
    			respContent = "解除绑定失败！";
    		}
    	}
    		
		return respContent;
	}*/
//	/**
//	 * 故障上报
//	 * @param terminalNo 
//	 * @param fromUserName
//	 * @return
//	 */
//	private static String faultReport(String openid) {
//		String respContent = null;
//		User user = userDAO.findById(openid);
//		
//		//该微信号未绑定过
//		if(user == null) {
//    		logger.info("该微信号未绑定");
//    		respContent = createRespMsg(NEWLINE);
//    	}
//		//已绑定
//    	else {
//    		logger.info("该微信号已绑定过");
//    		String timestamp = String.valueOf(System.currentTimeMillis());
//    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
//    		respContent = "<a href=\"" + MpInfo.HOST + "/servlet/FaultReportServlet?OpenId=%s&timestamp=%s&signature=%s\">请戳这里</a>进行故障上报！";
//    		respContent = String.format(respContent, openid, timestamp, signature);
//    	}
//    		
//		return respContent;
//	}
//	/**
//	 * 个人信息查看，若该微信号已绑定，则返回个人信息，若未绑定则返回绑定url
//	 * @param fromUserName
//	 * @return
//	 */
//	private static String infoCheck(String openid) {
//		String respContent = null;
//		User user = userDAO.findById(openid);
//		//该微信号未绑定过
//		if(user == null) {
//    		logger.info("该微信号未绑定");
//    		respContent = createRespMsg(NEWLINE);
//    	}
//		//已绑定
//    	else {
//    		logger.info("该微信号已绑定过");
//    		JSONObject jsonObject = CoreServiceFactory.getInstance().userInfoGet(user.getOpenId());
//    		WechatUser wechatUser = (WechatUser) JSONObject.toBean(jsonObject, WechatUser.class);
//    		
//    		respContent = "OpenId: " + user.getOpenId()+ "\n" + 
//					"终端编码：" + user.getTerminalId() + "\n" +
//					"销售员号：" + user.getSalerNo() + "\n" +
//					"昵称：" + wechatUser.getNickname() + "\n";
//    	}
//    		
//		return respContent;
//	}
}
